package cn.com.scooper.aop;

import cn.com.scooper.common.exception.BusinessException;
import cn.com.scooper.common.resp.APIRespJson;
import cn.com.scooper.common.resp.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * 基于Spring-rest的异常全局统一处理
 *
 * @author LuLihong
 * @date 2019-07-18
 **/
@RestControllerAdvice(annotations = RestController.class)
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(RestExceptionHandler.class);


    /**
     * 处理BusinessException异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<APIRespJson> handleBusinessException(BusinessException e) {
        LOG.error("操作失败:{} -> {}", e.getCode(), e.getMessage());

        APIRespJson apiRespJson = new APIRespJson(ResultCode.FAIL);
        return new ResponseEntity<>(apiRespJson, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理IllegalArgumentException异常
     * @param e
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<APIRespJson> handleIllegalArgumentException(IllegalArgumentException e) {
        LOG.error("操作失败: " + e.getMessage(), e);

        APIRespJson apiRespJson = new APIRespJson(ResultCode.PARAM_ERR);
        return new ResponseEntity<>(apiRespJson, HttpStatus.BAD_REQUEST);
    }

    /**
     * 处理Exception
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<APIRespJson> globalException(Exception e) {
        LOG.error("操作失败: " + e.getMessage(), e);

        APIRespJson apiRespJson = new APIRespJson(ResultCode.FAIL);
        return new ResponseEntity<>(apiRespJson, HttpStatus.BAD_REQUEST);
    }

}
